/*******************************************************************************
Physics.cpp

Notes:
*******************************************************************************/

#include "Physics.h"

//	CheckForCollision(...)
//		Checks the given entity against all other entities for collisions
//			pEntity - The entity to check with
Entity* Physics::CheckForCollision(Entity* pEntity)
{
	// Get the entity list from the manager
	std::map<EntityID, Entity*> entityList = EntityManager::GetManager()->GetEntityList();

	// Create an iterator
	std::map<EntityID, Entity*>::iterator it;

	// Store information about the given entity
	float x1, y1, w1, h1;

	x1 = pEntity->GetX();
	y1 = pEntity->GetY();
	w1 = pEntity->GetWidth();
	h1 = pEntity->GetHeight();

	// For each entity in the list...
	for(it = entityList.begin(); it != entityList.end(); it++)
	{
		// Grab a pointer to the entity
		Entity* pCheckEntity = it->second;

		// If the entity from the list is not the given entity
		if(pCheckEntity != pEntity)
		{
			// store information about the entity in the list
			float x2, y2, w2, h2;

			x2 = pCheckEntity->GetX();
			y2 = pCheckEntity->GetY();
			w2 = pCheckEntity->GetWidth();
			h2 = pCheckEntity->GetHeight();

			// If the entity is a boundary...
			if(pCheckEntity->IsBounds())
			{
				// If we're outside...
				if(x1 < x2 || x1 + w1 > x2 + w2 ||
					y1 < y2 || y1 + h1 > y2 + h2)
				{
					// ... return the entity
					return pCheckEntity;
				} // if
			} // if
			// otherwise...
			else
			{
				float left1 = x1;
				float right1 = x1 + w1;
				float top1 = y1;
				float bottom1 = y1 + h1;
				float left2 = x2;
				float right2 = x2 + w2;
				float top2 = y2;
				float bottom2 = y2 + h2;

				// If we're inside...
				if(((left1 > left2 && left1 < right2) || (right1 < right2 && right1 > left2)) &&
					((top1 > top2 && top1 < bottom2) || (bottom1 < bottom2 && bottom1 > top2)))
				{
					// ... return the entity
					return pCheckEntity;
				} // if
			} // else
		} // if
	} // for

	// We didn't find an entity
	return NULL;
} // CheckForCollision